package com.chat.service.impl;

import com.chat.enums.SearchFriendsStatusEnum;
import com.chat.mapper.FriendsRequestMapper;
import com.chat.mapper.MyFriendsMapper;
import com.chat.mapper.UsersMapper;
import com.chat.mapper.UsersMapperCustom;
import com.chat.pojo.FriendsRequest;
import com.chat.pojo.MyFriends;
import com.chat.pojo.Users;
import com.chat.pojo.vo.FriendRequestVO;
import com.chat.pojo.vo.MyFriendsVO;
import com.chat.service.UserService;
import com.chat.utils.FastDFSClient;
import com.chat.utils.FileUtils;
import com.chat.utils.QRCodeUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UsersMapper mapper;

    @Autowired
    private UsersMapperCustom usersMapperCustom;

    @Autowired
    private MyFriendsMapper friendsMapper;

    @Autowired
    private FriendsRequestMapper friendsRequestMapper;

    @Autowired
    private Sid sid;

    @Autowired
    private QRCodeUtils qrCodeUtils;

    @Autowired
    private FastDFSClient fastDFSClient;

    /**
     * 判断用户是否存在
     * @param username
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public boolean queryUserIsExist(String username) {
        Users user = new Users();
        user.setUsername(username);
        return mapper.selectOne(user) != null;
    }

    //使用事务注解
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Users queryUserLogin(String username,String password) {
        Example userExample = new Example(Users.class);

        Example.Criteria criteria = userExample.createCriteria();
        criteria.andEqualTo("username",username);
        criteria.andEqualTo("password",password);

        Users result = mapper.selectOneByExample(userExample);

        return result;
    }


    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Users userRegist(Users user) {
        String id = sid.nextShort();
        String userId = sid.nextShort();
        //TODO 为用户生成二维码
        //内容
        String content = "nichat_username:" + user.getUsername();
        //零时存放的路径，名字随机生成
        String qrCodePath = "H://qrCodeFile//" + userId + "_qrcode.png";
        //创建图片
        qrCodeUtils.createQRCode(qrCodePath,content);
        //上传图片
        MultipartFile file = FileUtils.fileToMultipart(qrCodePath);
        try {
            String fastdfs_path = fastDFSClient.uploadQRCode(file);
            user.setQrcode(fastdfs_path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        user.setId(userId);

        mapper.insert(user);
        return user;
    }

    /**
     * 更新用户头像信息
     * @param user
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users updateUserInfo(Users user) {
        //更新用户信息
        mapper.updateByPrimaryKeySelective(user);
        return queryUserById(user.getId());
    }

    /**
     * 查询用户的信息
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    Users queryUserById(String userid) {
        return mapper.selectByPrimaryKey(userid);
    }

    /**
     * 查询的前置条件
     * @param myUserId
     * @param friendUsername
     * @return
     */
    @Override
    public Integer preconditionSearchFriends(String myUserId, String friendUsername) {
        Users userInfo = queryUserInfoByUsername(friendUsername);
        //不存在
        if (userInfo == null) {
            return SearchFriendsStatusEnum.USER_NOT_EXIST.status;
        }
        //是自己
        if (userInfo.getId().equals(myUserId)) {
            return SearchFriendsStatusEnum.NOT_YOURSELF.status;
        }
        //已经是朋友
        Example fue = new Example(MyFriends.class);
        Example.Criteria fuc = fue.createCriteria();
        fuc.andEqualTo("myUserId",myUserId);
        fuc.andEqualTo("myFriendUserId",userInfo.getId());
        MyFriends myFriendsRel = friendsMapper.selectOneByExample(fue);
        if (myFriendsRel != null) {
            return SearchFriendsStatusEnum.ALREADY_FRIENDS.status;
        }

        return SearchFriendsStatusEnum.SUCCESS.status;
    }

    /**
     * 更具用户名查询信息
     * @param friendUsername
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Users queryUserInfoByUsername(String friendUsername) {
        Example ue = new Example(Users.class);
        Example.Criteria uc = ue.createCriteria();
        uc.andEqualTo("username",friendUsername);
        return mapper.selectOneByExample(ue);
    }

    @Override
    public void sendFriendRequest(String myUserId, String friendUsername) {
        //查询朋友的信息
        Users friend = queryUserInfoByUsername(friendUsername);

        //看数据库是否有该请求
        Example fre = new Example(FriendsRequest.class);
        Example.Criteria frc = fre.createCriteria();
        frc.andEqualTo("sendUserId",myUserId);
        frc.andEqualTo("acceptUserId",friend.getId());
        FriendsRequest requests = friendsRequestMapper.selectOneByExample(fre);
        if (requests == null) {
            //还未发送好友请求
            FriendsRequest record = new FriendsRequest();
            record.setId(sid.nextShort());
            record.setSendUserId(myUserId);
            record.setAcceptUserId(friend.getId());
            record.setRequesDataTime(new Date());
            friendsRequestMapper.insert(record);
            System.out.println("成功发送添加好友请求");
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<FriendRequestVO> queryFriendRequestList(String acceptUserId) {
        return usersMapperCustom.queryFriendRequestList(acceptUserId);
    }

    /**
     * 删除好友请求
     *
     * @param sendUserId
     * @param acceptUserId
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void deleteFriendRequest(String sendUserId, String acceptUserId) {
        Example fre = new Example(FriendsRequest.class);
        Example.Criteria frc = fre.createCriteria();
        frc.andEqualTo("sendUserId",sendUserId);
        frc.andEqualTo("acceptUserId",acceptUserId);

        friendsRequestMapper.deleteByExample(fre);
    }

    /**
     * 通过好友请求
     *
     * @param sendUserId
     * @param acceptUserId
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void passFriendRequest(String sendUserId, String acceptUserId) {
        //在好友关系表中添加双向关系，即两个反向的关系
        saveFriends(sendUserId,acceptUserId);
        saveFriends(acceptUserId,sendUserId);

        //删除好友请求表中的数据
        deleteFriendRequest(sendUserId,acceptUserId);
    }

    /**
     * 查询好友列表
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public List<MyFriendsVO> queryMyFriends(String userId) {
        return usersMapperCustom.queryMyFriends(userId);
    }

    /**
     * 保存好友关系
     */
    @Transactional(propagation = Propagation.SUPPORTS)
    public void saveFriends(String sendUserId, String acceptUserId) {
        MyFriends myFriends = new MyFriends();
        myFriends.setId(sid.nextShort());
        myFriends.setMyUserId(acceptUserId);
        myFriends.setMyFriendUserId(sendUserId);
        friendsMapper.insert(myFriends);
    }
}
